package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neuedu.entity.Nursecontent;
import com.neuedu.entity.Nurselevelitem;
import com.neuedu.mapper.NurselevelitemMapper;
import com.neuedu.service.NursecontentService;
import com.neuedu.service.NurselevelitemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 护理等级项目对应表 服务实现类
 * </p>
 *
 * @author wangyu
 * @since 2025-10-23
 */
@Service
public class NurselevelitemServiceImpl extends ServiceImpl<NurselevelitemMapper, Nurselevelitem> implements NurselevelitemService {
    @Resource
    PlatformTransactionManager transactionManager;
    @Resource
    NursecontentService nursecontentService;
    @Override
    public boolean add(Integer levelId, Integer[] itemIds) {
        UpdateWrapper<Nurselevelitem> wrapper = new UpdateWrapper<>();
        wrapper.eq("level_id", levelId);
        List<Nurselevelitem> list = new ArrayList<>();
        for (Integer itemId : itemIds) {
            list.add(new Nurselevelitem(levelId, itemId));
        }
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            this.remove(wrapper);
            this.saveBatch(list);
            transactionManager.commit(status);
            return true;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    @Override
    public List<Integer> list(Integer levelId) {
        QueryWrapper<Nurselevelitem> wrapper = new QueryWrapper<>();
        wrapper.eq("level_id", levelId)
                .select("item_id");
        return this.list(wrapper).stream().map(Nurselevelitem::getItemId).toList();
    }

    @Override
    public List<Nursecontent> getItem(Integer levelId) {

        return nursecontentService.getByIds(this.list(levelId));
    }
}
